import React, { PropTypes } from 'react';
import {
  View,
  Text,
  TextInput,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
  DeviceEventEmitter,
  Platform,
  Image,
} from 'react-native';
import DatePicker from 'react-native-datepicker';
import PxToDp from '../../../utils/PxToDp';
import NavCon from '../../Public/NavCon';
import { changeVisitReminder, addVisitReminder, fetchMoreVisit } from '../../../actions/MyCustomerDetailAction';

export default class ChangeVisitReminder extends React.Component {
  constructor(props) {
    super(props);
    const { remind, type } = this.props;
    this.state = {
      vType: type,
      rType: type,
      visitDate: '',
      remindDate: '',
      visitTime: '20:00',
      remindTime: '20:00',
      visitDateTime: remind ? remind.visit_at ? remind.visit_at : '' : '',
      remindDateTime: remind ? remind.remind_at ? remind.remind_at : '' : '',
      comment: remind ? remind.comment : '',
    };
  }
  static propTypes = {
    title: PropTypes.string,
  };

  _goBack() {
    const { dispatch, id } = this.props;
    dispatch(fetchMoreVisit(id, () => {
      this.props.navigator.pop();
    }));
  }

  _onVisitDateChange(visitDateTime) {
    this.setState({ visitDateTime });
  }

  _onRemindDateChange(remindDateTime) {
    this.setState({ remindDateTime });
  }

  _completed(visitId) {
    const { dispatch, id, type } = this.props;
    const data = {};
    data.visit_at = this.state.visitDateTime;
    data.remind_at = this.state.remindDateTime;
    data.comment = this.state.comment;
    if (visitId) {
      data.id = visitId;
    }

    if (type === 'change') {
      dispatch(changeVisitReminder(data, id, () => {
        dispatch(fetchMoreVisit(id));
      }));
    } else {
      dispatch(addVisitReminder(data, id, () => {
        dispatch(fetchMoreVisit(id));
      }));
    }
  }

  _getDate() {
    const date = new Date();
    const year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    const hours = date.getHours();
    const minutes = date.getMinutes();
    if (month.toString().length === 1) {
      month = `0${month}`;
    }
    if (day.toString().length === 1) {
      day = `0${day}`;
    }
    return `${year}.${month}.${day} ${hours}:${minutes}`;
  }

  render() {
    const { data, remind, type } = this.props;
    const { user } = data;
    const { username } = user;
    const length = username.length;
    const name = username.substring(length - 2, length).toUpperCase();
    // const vPosition = this.state.vType === 'add' ? 'absolute' : 'relative';
    // const vLeft = this.state.vType === 'add' ? PxToDp(30) : 0;
    // const rPosition = this.state.rType === 'add' ? 'absolute' : 'relative';
    // const rLeft = this.state.Type === 'add' ? PxToDp(30) : 0;
    const sex = user.sex === '男' ?
    require('../../../img/home/cule-list-men.png') :
    require('../../../img/home/cule-list-wamen.png');
    return (
      <View style={[styles.flex, styles.bgColor]}>
        <NavCon
          style={[styles.flex, styles.top]}
          currentTitle={this.props.title}
          bgColor="#fff"
          onPress={() => this._goBack()}
        />
        <ScrollView contentContainerStyle={[styles.flex]}>
          <View style={styles.head}>
            <View style={[styles.nameIcon, styles.center]}>
              <Text style={styles.nameText}>{name}</Text>
            </View>
          </View>

          <View style={styles.contaner}>
            <View style={[styles.row, styles.nameView]}>
              <Text style={styles.name}>{username}</Text>
              <Image source={sex} />
            </View>
            <View style={styles.baseInfo}>
              <Text style={styles.phone}>{user.phone}</Text>
            </View>
            <Text style={[styles.timeText, styles.visitText]}>客户拜访的时间</Text>
            <View style={[styles.timeInput]}>
              <View style={styles.row}>
                <Image source={require('../../../img/detail/cule-choose-time.png')} />
                {
                 this.state.vType === 'add' ? <Text style={styles.remindTime}>请添加拜访时间</Text> : null
                }
              </View>

              <View style={[styles.datepicker]}>
                <DatePicker
                  style={styles.dpView}
                  date={this.state.visitDateTime}
                  mode="datetime"
                  format="YYYY.MM.DD HH:mm"
                  confirmBtnText="确认"
                  cancelBtnText="取消"
                  showIcon={false}
                  customStyles={{
                    dateIcon: {
                      top: 4,
                    },
                    dateText: {
                      marginLeft: PxToDp(0),
                      color: '#333',
                      fontSize: PxToDp(12),
                    },
                    dateInput: {
                      borderRadius: PxToDp(2),
                      height: this.state.vType === 'change' ? PxToDp(28) : 0,
                      width: this.state.vType === 'change' ? PxToDp(100) : 0,
                      borderWidth: 0,
                    },
                  }}
                  onDateChange={(datetime) => {
                    if (datetime < this._getDate()) {
                      DeviceEventEmitter.emit('showToast', '拜访时间应晚于当前时间，请重新输入！');
                    } else {
                      this._onVisitDateChange(datetime);
                      this.setState({ vType: 'change' });
                    }
                  }}
                />
              </View>
            </View>
            <Text style={[styles.timeText, styles.visitText]}>短信提醒的时间</Text>
            <View style={[styles.timeInput]}>
              <View style={styles.row}>
                <Image source={require('../../../img/detail/cule-choose-time.png')} />
                {
                  this.state.rType === 'add' ? <Text style={styles.remindTime}>请添加提醒时间</Text> : null
                }
              </View>

              <View style={[styles.datepicker]}>
                <DatePicker
                  style={styles.dpView}
                  date={this.state.remindDateTime}
                  mode="datetime"
                  format="YYYY.MM.DD HH:mm"
                  confirmBtnText="确认"
                  cancelBtnText="取消"
                  showIcon={false}
                  customStyles={{
                    dateIcon: {
                      top: 4,
                    },
                    dateText: {
                      marginLeft: PxToDp(0),
                      color: '#333',
                      fontSize: PxToDp(12),
                    },
                    dateInput: {
                      borderRadius: PxToDp(2),
                      height: this.state.rType === 'change' ? PxToDp(28) : 0,
                      width: this.state.rType === 'change' ? PxToDp(100) : 0,
                      borderWidth: 0,
                    },
                  }}
                  onDateChange={(datetime) => {
                    if (datetime.toString() > this.state.visitDateTime) {
                      DeviceEventEmitter.emit('showToast', '提醒时间应早于拜访时间，请重新输入！');
                    } else if (datetime.toString() < this._getDate()) {
                      DeviceEventEmitter.emit('showToast', '提醒时间应晚于当前时间，请重新输入！');
                    } else {
                      this.setState({ rType: 'change' });
                      this._onRemindDateChange(datetime);
                    }
                  }}
                />
              </View>
            </View>

            <TextInput
              placeholder={'短信提醒内容（选填）'}
              multiline
              maxLength={130}
              onChangeText={comment => this.setState({ comment })}
              value={this.state.comment}
              style={[styles.smInput]}
              underlineColorAndroid="transparent"
            />
          </View>

        </ScrollView>
        <View style={styles.bottomWrapper}>
          <TouchableOpacity
            activeOpacity={0.6}
            style={[styles.center, styles.button, styles.cancelWrapper]}
            onPress={() => this._goBack()}
          >
            <Text style={styles.cancel}>取消</Text>
          </TouchableOpacity>
          <TouchableOpacity
            activeOpacity={0.6}
            style={[styles.center, styles.button, styles.completedWrapper]}
            onPress={() => {
              const id = remind ? remind.id : null;
              const toast = type === 'change' ? '修改拜访提醒成功！' : '添加拜访提醒成功';
              DeviceEventEmitter.emit('showToast', toast);
              this._completed(id);
              this._goBack();
            }}
          >
            <Text style={styles.completed}>完成</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  flex: {
    flex: 1,
  },
  bgColor: {
    backgroundColor: '#F9F9F9',
    marginTop: Platform.OS === 'ios' ? 20 : 0,
  },
  center: {
    justifyContent: 'center',
    alignItems: 'center',
  },
  nameIcon: {
    width: PxToDp(54),
    height: PxToDp(54),
    borderRadius: PxToDp(28),
    backgroundColor: '#30c8f9',
  },
  nameText: {
    color: '#fff',
    fontSize: PxToDp(14),
  },
  name: {
    marginRight: PxToDp(13),
    color: '#000000',
    fontSize: PxToDp(15),
  },
  phone: {
    color: '#ffffff',
    backgroundColor: '#D6CEAA',
    fontSize: PxToDp(12),
    paddingTop: PxToDp(4),
    paddingLeft: PxToDp(8),
    paddingBottom: PxToDp(4),
    paddingRight: PxToDp(8),
  },
  remindTime: {
    fontSize: PxToDp(14),
    color: '#8b8c8e',
    marginLeft: PxToDp(8),
  },
  bottomWrapper: {
    flexDirection: 'row',
    width: '100%',
    borderStyle: 'solid',
    borderColor: '#ddd',
    borderWidth: PxToDp(1),
  },
  button: {
    width: '50%',
    height: PxToDp(48),
  },
  cancelWrapper: {
    borderStyle: 'solid',
    borderColor: '#b7b7b7',
    borderRightWidth: PxToDp(1),
    backgroundColor: '#f0f0f0',
  },
  completedWrapper: {
    backgroundColor: '#458fff',
  },
  cancel: {
    fontSize: PxToDp(15),
    color: '#000000',
  },
  completed: {
    fontSize: PxToDp(16),
    color: '#fff',
  },
  datepicker: {
    position: 'absolute',
    flex: 1,
    overflow: 'hidden',
    zIndex: 0,
  },
  contaner: {
    backgroundColor: '#FFFFFF',
    zIndex: 1,
    marginTop: PxToDp(47),
    borderColor: '#e4e4e4',
    borderStyle: 'solid',
    borderWidth: PxToDp(0.5),
    paddingBottom: PxToDp(33),
    paddingLeft: PxToDp(20),
    paddingRight: PxToDp(20),
  },
  head: {
    alignItems: 'center',
    top: PxToDp(20),
    zIndex: 999,
    position: 'absolute',
    justifyContent: 'center',
    width: '100%',
  },
  row: {
    flexDirection: 'row',
  },
  baseInfo: {
    alignItems: 'center',
    paddingTop: PxToDp(7),
  },
  nameView: {
    height: PxToDp(53),
    alignItems: 'flex-end',
    justifyContent: 'center',
  },
  timeText: {
    color: '#8b8c8e',
    fontSize: PxToDp(15),
  },
  visitText: {
    marginTop: PxToDp(22),
  },
  timeInput: {
    height: PxToDp(38),
    backgroundColor: '#efefef',
    paddingLeft: PxToDp(15),
    marginBottom: PxToDp(8),
    marginTop: PxToDp(14),
    justifyContent: 'center',
  },
  smInput: {
    backgroundColor: '#efefef',
    paddingLeft: PxToDp(13),
    paddingRight: PxToDp(13),
    height: PxToDp(100),
    marginTop: PxToDp(22),
    textAlignVertical: 'top',
  },
  dpView: {
    width: '100%',
  },
});
